//
//  DiscoveryTableViewController.m
//  Wifi
//
//  Created by srulos on 2017/6/9.
//  Copyright © 2017年 srulos. All rights reserved.
//

#import "DiscoveryTableViewController.h"
#import "WifiHeader.h"
#import "DiscoverTableViewCell.h"
#import "DiscoverLeanCloudTableViewCell.h"
#import "AppDelegate.h"
#import "DiscoverLeanCloudWebViewController.h"
#import "GADTableViewCell.h"

@interface DiscoveryTableViewController ()<DiscoverTableViewCellDelegate>
{
    NSString * m_currentTimestamp;//百思不得姐分页用
    MJRefreshBaseView * m_refreshHeadView;
    MJRefreshBaseView * m_refreshFootView;
    NSMutableArray * m_arrayDatas;
    LongImageView * m_longImageView;
}
@end

@implementation DiscoveryTableViewController
@synthesize m_title;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    m_arrayDatas = [[NSMutableArray alloc]init];
    
    if (IS_CHINESE) {//百思不得姐
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//进入全屏
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏
        
        [self addHeader];
        [self addFooter];
        
        m_currentTimestamp = @"0";
        [self loadDataFromBaiSiBuDeJie];
    }
    else{//leancloud
        [self loadDataFromLeanCloud];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

// 进入全屏
-(void)begainFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = NO;
    
    //强制归正：
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val =UIInterfaceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return m_arrayDatas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (IS_CHINESE) {
        AVObject * dic = [m_arrayDatas objectAtIndex:indexPath.row];
        if (((NSString *)[dic valueForKey:@"AD"]).length > 0) {
            if ([[UIDevice currentDevice].model rangeOfString:@"iPad"].length > 0) {
                return KSCREEN_WIDTH * 0.8;
            }else{
                return KSCREEN_WIDTH ;
            }
        }else{
            return 400.0f;
        }
    }
    else{
        return 275.0f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * cellIdentifier = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];
    
    if (IS_CHINESE) {//百思不得姐
        NSMutableDictionary * dic = [m_arrayDatas objectAtIndex:indexPath.row];
        
        if ([dic objectForKey:@"AD"] != nil) {//google ad
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[GADTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                GADTableViewCell * gadTableViewCell = (GADTableViewCell*)cell;
                [gadTableViewCell setup:self];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }
        else{//baisi data
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = VIEW_INIT_NIB(DiscoverTableViewCell);
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            DiscoverTableViewCell * discoverTableViewCell = (DiscoverTableViewCell*)cell;
            discoverTableViewCell.delegate = self;
            [discoverTableViewCell setup:dic];
            return cell;
        }
    }
    else{//leancloud
        AVObject * dic = [m_arrayDatas objectAtIndex:indexPath.row];
        
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = VIEW_INIT_NIB(DiscoverLeanCloudTableViewCell);
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        DiscoverLeanCloudTableViewCell * discoverTableViewCell = (DiscoverLeanCloudTableViewCell*)cell;
        [discoverTableViewCell setup:dic];
        return cell;
    }
}

/*************************************** leancloud *************************************/
#pragma mark load data from 百思不得姐
- (void)loadDataFromBaiSiBuDeJie
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString * requestUrl = [self getBaiSiBuDeJieRequestUrl];
        
        if (requestUrl != nil) {
            WQSimpleHttpHelper * simpleHttpHelper = [[WQSimpleHttpHelper alloc]init];
            WQHttpRequest * request = [[WQHttpRequest alloc]initWithUrlAndParam:requestUrl param:nil];
            
            NSMutableDictionary * dicResp = [simpleHttpHelper execute2Dictionary:request];
            
            m_currentTimestamp = dicResp[@"info"][@"np"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (m_refreshHeadView != nil && [m_refreshHeadView isRefreshing]) {
                    [m_refreshHeadView endRefreshing];
                    [m_arrayDatas removeAllObjects];
                }
                
                BOOL isLoadMore = NO;
                if (m_refreshFootView != nil && [m_refreshFootView isRefreshing]) {
                    [m_refreshFootView endRefreshing];
                    isLoadMore = YES;
                }
                
                NSMutableArray * dataList = [dicResp objectForKey:@"list"];
                for (int i = 0 ; i < dataList.count; i++) {
                    NSMutableDictionary * dataDic = [dataList objectAtIndex:i];
                    NSString * dataType = [dataDic objectForKey:@"type"];
                    if ([dataType isEqualToString:@"image"] ||
                        [dataType isEqualToString:@"gif"] ||
                        [dataType isEqualToString:@"video"]) {//只显示这三种的数据
                        [m_arrayDatas addObject:dataDic];

                        //添加广告
                        if (i % 10 == 0 && IS_PASS) {
                            [m_arrayDatas addObject:[self addAdvertising]];
                        }
                    }
                }
                
                [self.tableView reloadData];
            });
        }
    });
}

-(NSDictionary *)addAdvertising
{
    NSMutableDictionary * adDic = [NSMutableDictionary  dictionary];
    [adDic setObject:@"AD" forKey:@"AD"];
    return adDic;
}

- (NSString*)getBaiSiBuDeJieRequestUrl
{
    if ([m_title isEqualToString:K_NSLOCAL(@"Recom")]) {
       return [NSString stringWithFormat:@"http://s.budejie.com/topic/list/jingxuan/1/bs0315-iphone-4.5.6/%@-20.json",m_currentTimestamp];
    }
    else if([m_title isEqualToString:K_NSLOCAL(@"Video")]){
        return [NSString stringWithFormat:@"http://s.budejie.com/topic/list/jingxuan/41/bs0315-iphone-4.5.6/%@-20.json",m_currentTimestamp];
    }
    else if([m_title isEqualToString:K_NSLOCAL(@"Image")]){
        return [NSString stringWithFormat:@"http://s.budejie.com/topic/list/jingxuan/10/bs0315-iphone-4.5.6/%@-20.json",m_currentTimestamp];
    }
    return nil;
}

#pragma mark data reload and load more
- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        m_refreshHeadView = refreshView;
        m_currentTimestamp = @"0";
        [self loadDataFromBaiSiBuDeJie];
    };
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        m_refreshFootView = refreshView;
        [self loadDataFromBaiSiBuDeJie];
    };
}

#pragma mark discover tableviewcell delegate
- (void)onShowImage:(NSData *)imageData isGif:(BOOL)isGif
{
    m_longImageView = [LongImageView showInWindow:imageData isGif:isGif];
}

- (void)autoScrollToTop
{
    if (m_longImageView != nil && [m_longImageView superview] != nil) {
        [m_longImageView setContentOffset:CGPointMake(0,0) animated:YES];
    }
    else{
        [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
    }
}

/*************************************** leancloud *************************************/
#pragma mark data load from leancloud
- (void)loadDataFromLeanCloud
{
    AVQuery *query = [AVQuery queryWithClassName:@"DiscoverCategoryItem"];
    [query whereKey:@"category_title" equalTo:m_title];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        if (objects != nil && objects.count > 0) {
            [m_arrayDatas addObjectsFromArray:objects];
            [self.tableView reloadData];
        }
    }];
}

 #pragma mark - Table view delegate
 
 // In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     if (IS_CHINESE) {//百思不得姐，没有任何操作
     }
     else{//进入页面
         AVObject * dic = [m_arrayDatas objectAtIndex:indexPath.row];
         
         VC_INIT_NC_WITH_NIB_NAME_VC_NAME(DiscoverLeanCloudWebViewController, vc, nav);
         vc.m_url = [dic objectForKey:@"link"];
         vc.title = [dic objectForKey:@"title"];
         
         [self presentViewController:nav animated:YES completion:nil];
     }
 }
@end
